<?php
/**
 * @author yuanyitian
 * @date 2023/6/5 20:37
 */
require_once "autoload.php";

use utils\redis;


header("content-type:text/html;charset=utf8");
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);

$url=parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if($url!=='/index.php'){//非法请求路径检测
    echo response(out_error("非法请求1！"));
    return ;
}

$path = explode("/", $_GET["path"]);
$fun = $path[count($path) - 1];
array_pop($path);
$path = implode("\\", $path);
//RSA解密算法
//openssl_public_decrypt(urldecode(file_get_contents("php://input")), $decrypted, $GLOBALS['request_public_key']);
//AES解密算法
$decrypted=openssl_decrypt(base64_decode(urldecode(file_get_contents("php://input"))), 'AES-256-CBC', $GLOBALS['aes_key'], OPENSSL_RAW_DATA, $GLOBALS['aes_iv']);
//填充链路去除
$decrypted=str_replace('','',$decrypted);

if(empty($decrypted)){//空值检测。空多半为非法数据
    echo response(out_error("非法请求2！"));
    return ;
}
//if(!preg_match('/^[\{},:\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/',$decrypted)){//json合法性检测
//    echo response(out_error("非法请求3！"));
//    return ;
//}


$data=json_decode($decrypted, true);

//$not_token=[
//    'login','logout','checkLoginByQrcode','init','test','becomeVip'
//];
$not_token=[
    'login','logout','test','phone','add_wechat_user','loginForSuper','getRichtextInfoById'
];

if(in_array($fun, $not_token)){
    echo response((new $path())->$fun($data));
}else{
    if(array_key_exists("HTTP_X_TOKEN", $_SERVER)){
        $redis = redis::con();
        $token_key=$_SERVER["HTTP_X_TOKEN"];
        $token=$redis->get($token_key);
        if($token){
            $res=$redis->expire($token_key,1800);
            $redis->close();
            $data["login_user_id"]=(int)$token;
            $data["login_token"]=$token_key;
            echo response((new $path())->$fun($data));
        }else{
            $redis->close();
            echo response(out_error_token());
        }
    }else{
        echo response(out_error("非法请求4！"));
    }
}




